#define DEBUG 1

#include <stdio.h>
#include <stdbool.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <string.h>

#include "gdbstub_fe.h"

#define MAX_LEN 1024 // 接收浏览器数据
#define PORT 3333    // 服务器监听端口
#define LISTEN_BACKLOG 1

// ================================================================
// Initialize gdbstub socket, return the accepted client fd

int socket_stub(FILE *logfile)
{
    int sfd, cfd;
    int reuse = 1;
    struct sockaddr_in server_addr; // 地址结构体
    char buf[MAX_LEN];

    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(PORT);

    sfd = socket(AF_INET, SOCK_STREAM, 0);

    if (sfd == -1)
    {
#if DEBUG
        {
            fprintf(logfile, "ERROR: Socket creat fail! \n");
            printf("ERROR: Socket creat fail! \n");
        }
#endif
        return -1;
    }

    setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&reuse, sizeof(int));

    if (bind(sfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
    {
#if DEBUG
        {
            fprintf(logfile, "ERROR: Bind socket creat fail! \n");
            printf("ERROR: Bind socket creat fail! \n");
        }
#endif
        return -1;
    }

    if (listen(sfd, LISTEN_BACKLOG) == -1)
    {
#if DEBUG
        {
            fprintf(logfile, "ERROR: listen socket creat fail! \n");
            printf("ERROR: listen socket creat fail! \n");
        }
#endif
        return -1;
    }

    cfd = accept(sfd, NULL, NULL);
    {
#if DEBUG
        {
            fprintf(logfile, "Accept socket! \n");
            printf("Accept socket! \n");
        }
#endif
    }

    return cfd;
}

int main(int argc, char **argv)
{
    Gdbstub_FE_Params params;

    // TODO: open logfile to record gdbstub communications w. GDB and Debug Module
    params.logfile = fopen("./gdbstub.log", "a+");

    // TODO: listen on socket/PTY/... for GDB connection
    params.gdb_fd = socket_stub(params.logfile);
    
    //stop fd not use.
    params.stop_fd = -1;

    main_gdbstub(&params);
}
